package com.itany.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itany.dao.ManagerUserDao;
import com.itany.entity.ManagerUser;
import com.itany.exception.ManagerUserExistsException;
import com.itany.exception.ManagerUserIdNotException;
import com.itany.exception.ManagerUserNotExistsException;
import com.itany.service.ManagerUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Author：汤小洋
 * Date：2019-12-19 11:13
 * Description：<描述>
 */
@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class ManagerUserServiceImpl implements ManagerUserService {

    @Autowired
    private ManagerUserDao managerUserDao;

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    public ManagerUser login(ManagerUser user) throws ManagerUserNotExistsException {
        ManagerUser u = managerUserDao.selectByUsernameAndPassword(user);
        if(u==null){
            throw new ManagerUserNotExistsException("用户名或密码不正确");
        }
        return u;
    }

    @Override
    public PageInfo<ManagerUser> findByPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<ManagerUser> users = managerUserDao.findByPage();
        PageInfo<ManagerUser> pageInfo = new PageInfo<>(users);
        return pageInfo;
    }

    @Override
    public void addUser(ManagerUser managerUser) throws ManagerUserExistsException {
        ManagerUser user = managerUserDao.selectByUsername(managerUser.getUsername());
        System.out.println("----------");
        System.out.println(user);

        if (user!= null){
            throw new ManagerUserExistsException("用户名已存在");
        }
        managerUserDao.insertUser(managerUser);
    }

    @Override
    public void modifyUser(ManagerUser user) throws ManagerUserExistsException {
        ManagerUser u = managerUserDao.selectByUsername(user.getUsername());
        if (u!=null){
            throw new ManagerUserExistsException("用户名已存在");
        }
        managerUserDao.updateUser(user);
    }

    @Override
    public void deleteUser(Integer id) {
        managerUserDao.deleteUser(id);
    }

    @Override
    public ManagerUser findByUserId(Integer id) throws ManagerUserIdNotException {
        ManagerUser user = managerUserDao.selectByUserId(id);
        if (user == null){
            throw new ManagerUserIdNotException("用户id不存在!");
        }
        return user;
    }

    @Override
    public void modifyPassword(ManagerUser user) {
        managerUserDao.updateUserPassword(user);
    }
}
